<?php

namespace app\admin\controller;

use tests\thinkphp\library\think\dbTest;
use think\Controller;
use think\Db;
use app\admin\model\Banner;
use app\admin\model\Goods;
use app\admin\model\Member;
use app\admin\model\Category;
use app\admin\model\Notice;
use think\Validate;
use OSS\OssClient;
use OSS\Core\OssException;
class Shoppingmall extends Base
{

    //控制台
    public function lists()
    {
        if (request()->isAjax()) {
            $this->fetch();
        } else {
            return $this->fetch('user/user/lists');
        }
    }

    //商城图片
    public function picture()
    {
        if (request()->isAjax()){
//            $res = Banner::all();
//            foreach ($res as $k => $v){
//                $type = $this->pay_type();
//                $res[$k]['type'] = $type[$v['type']];
//                $res[$k]['create_time'] = date('Y-m-d,H:i:s', $v['create_time']);
//                $res[$k]['logo']  = $this->url.'/uploads/banner/'.$res[$k]['logo'];
//            }
//            $this->ajaxReturn('', $res);
//            $this->fetch();
            $list = Db::name('banner')->order('id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_map;
            unset($where['page']);unset($where['op']);unset($where['limit']);
            (!empty($where)) ? $data = $list->whereor($where)->select() : $data = $list->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $type = $this->pay_type();
                $data[$k]['type'] = $type[$v['type']];
                $data[$k]['create_time'] = date('Y-m-d,H:i:s', $v['create_time']);
                $data[$k]['logo']  = $this->url.'/uploads/banner/'.$data[$k]['logo'];
            }
            $this->ajaxReturn('', $data, $total);
        } else {
            return $this->fetch('shoppingmall/lists');
        }
    }

    //上传图片
    public function upload_img()
    {
        $this->_param['img_src'] = isset($_FILES['img_src']) ? $_FILES['img_src'] : '';
        $validate = [
            ['name', 'require', '图片备注不能为空',],
            ['type', 'require', '类型不能为空'],
            ['img_src', 'require', '请选择图片'],
        ];
        $test = $this->validate($this->_param, $validate);
        if ($test !== true) {
            $this->ajaxReturn($test, 201);
        }
        $file = request()->file('img_src');
        if ($file) {
            $path = ROOT_PATH . 'public/uploads/banner';
            $info = $file->rule('uniqid')->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->move($path);

            //上传阿里云OSS
            if(true)
            {
                $root = $_SERVER['DOCUMENT_ROOT'];
                if (is_file($root . '/../extend/oss/autoload.php')) {
                    require_once $root . '/../extend/oss/autoload.php';
                }
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                try {
                    $ossClient->uploadFile($this->bucket, 'uploads/banner/'.$info->getSaveName(), $path.'/'.$info->getSaveName());
                    @unlink($_SERVER['DOCUMENT_ROOT'] .'/uploads/banner/'.$info->getSaveName());
                } catch (OssException $e) {
                    printf($e->getMessage() . "\n");
                    return;
                }
            }
            if ($info){
                $user = new Banner;
                $user->data([
                    'name' => $this->_param['name'],
                    'type' => $this->_param['type'],
                    'logo_url' => $this->_param['logo_url'],
                    'create_time' => time(),
                    'logo' => $info->getSaveName()
                ]);
                $en = $user->save();
                if ($en) {
                    $this->ajaxReturn('上传图片成功', 200, '', 200);
                } else {
                    $this->ajaxReturn('保存失败');
                }
            } else {
                // 上传失败获取错误信息
                $this->ajaxReturn($file->getError(), 201, '', 201);
            }
        }
    }

    //更改图片
    public function update_img()
    {
        $this->_param['img_src'] = isset($_FILES['img_src']) ? $_FILES['img_src'] : '';
//        dump($this->_param);die;
        $validate = [
            ['img_src', 'require', '请选择图片'],
        ];
        $test = $this->validate($this->_param, $validate);
        if ($test !== true) {
            $this->ajaxReturn($test, 201);
        }
        $file = request()->file('img_src');
        if ($file) {
            $path = ROOT_PATH . 'public/uploads/banner';
            $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move($path);
//            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');


            //上传阿里云OSS
            if(true)
            {
                $root = $_SERVER['DOCUMENT_ROOT'];
                if (is_file($root . '/../extend/oss/autoload.php')) {
                    require_once $root . '/../extend/oss/autoload.php';
                }
                $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                try {
                    $ossClient->uploadFile($this->bucket, 'uploads/banner/'.$info->getSaveName(), $path.'/'.$info->getSaveName());
                    unlink($_SERVER['DOCUMENT_ROOT'] .'/uploads/banner/'.$info->getSaveName());
                } catch (OssException $e) {
                    printf($e->getMessage() . "\n");
                    return;
                }
            }
            if ($info) {
                $user = new Banner;
                $data = [
                    'logo' =>  $info->getSaveName()
                ];
                $en = $user->where('id', $this->_param['id'])->Update($data);
                if ($en) {
                    $this->ajaxReturn('修改图片成功', 200, '', 200);
                } else {
                    $this->ajaxReturn('保存失败');
                }
            } else {
                $this->ajaxReturn($file->getError(), 201, '', 201);
            }
        }
    }

    //图片显示
    public function del($id)
    {
        $res = Banner::where('id', 'in', $id)->update(['status' => 1]);
        if ($res !== false) {
            $this->success('显示成功!',url('picture'),200);
        } else {
            $this->error('显示失败!', '');
        }
    }

    //取消显示
    public function cancelshow($id)
    {
        $res = Banner::where('id', 'in', $id)->update(['status' => 0]);
        if ($res !== false) {
            $this->success('取消显示成功!', url('picture'), 200);
        } else {
            $this->error('取消显示失败!', '');
        }//YOU
    }

    //删除图片
    public function delete_img(){
        $id = $this->_param['id'];
        $rk=   Banner::destroy(['id'=>$id]);
        if($rk){
            $this->ajaxReturn('删除图片成功',200);
        }else{
            $this->ajaxReturn('删除图片失败',201);
        }
    }

    //商城订单
    public function order_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('v_order')->order('order_id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_map;
            unset($where['page']);unset($where['op']);unset($where['limit']);
            (!empty($where)) ? $data = $list->whereor($where)->select() : $data = $list->select();
            $this->assign('map', $this->_param);
            $order_statue = $this->order_statue();
            foreach ($data as $k => $v) {
                $data[$k]['status'] = $order_statue[$v['status']];
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('shoppingmall/order_list');
        }
    }

    //商城订单详情
    public function info($order_id)
    {
        $list = db('v_order')->where('order_id', $order_id)->find();
        $list['create_time'] = date('Y-m-d,h:i:s', $list['create_time']);
        $status = $this->order_statue();
        $list['status'] = $status[$list['status']];
        $list['pay_time'] = date('Y-m-d,h:i:s', $list['pay_time']);
        $list['img'] = $this->url.'/uploads/goods/'.$list['image'];
        $this->assign('list', $list);
        return $this->fetch();
    }

    //商品列表
    public function goods_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('goods');
            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            $where['is_jp']=0;
//            dump($this->_map);die;status=1;
            (!empty($where)) ? $list = $list->where('status','<>',-3)->where($where)->order('goods_id desc') : $list = $list->where('status','<>',-3)->order('goods_id desc');
            $t_list = clone ($list);
            $total = $t_list->count();
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data=$list->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $user = Member::get(['id' => $v['uid']]);
                $data[$k]['uname'] = $user['nickname'];
                $Category = Category::get(['id' => $v['category_id']]);
                $data[$k]['category'] = $Category->name;
                $status = $this->goods_status();
                $data[$k]['goods_status'] = $status[$v['status']];
                $data[$k]['is_hot_str'] =$data[$k]['is_hot']?'是':'否';
                $data[$k]['is_jp_str'] =$data[$k]['is_jp']?'竞拍':'普通';
                $data[$k]['btn_str'] =$data[$k]['is_jp']?'精品':'热门';
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('shoppingmall/goods_list');
        }
    }

    //商品列表
    public function goods_jp_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('goods');
//            $total = $list->count();

            $where = $this->_map;
            $where['is_jp']=1;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            $where['is_jp']=1;

            if(isset($this->_param['jp_status'])&&$this->_param['jp_status']!='')
            {
                $jp_status=$this->_param['jp_status'];
                if($jp_status==0)
                {
                    $where['status']=0;
                }
                else if($jp_status==1)
                {
                    $where['end_time']=array('>',time());
                }
                else
                {
                    $where['end_time']=array('<',time());
                }
            }

            (!empty($where)) ? $list = $list->where('status','<>',-3)->where($where)->order('goods_id desc') : $list = $list->where('status','<>',-3)->order('goods_id desc');
            $t_list = clone ($list);
            $total = $t_list->count();
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data = $list->select();
//            dump($data);die;
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $user = Member::get(['id' => $v['uid']]);
                $data[$k]['uname'] = $user['nickname'];
                $Category = Category::get(['id' => $v['category_id']]);
                $data[$k]['category'] = $Category->name;
                $status = $this->goods_status();
                $data[$k]['goods_status'] = $status[$v['status']];
                $data[$k]['is_hot_str'] =$data[$k]['is_hot']?'是':'否';
                $data[$k]['is_jp_str'] =$data[$k]['is_jp']?'竞拍':'普通';
                $data[$k]['btn_str'] =$data[$k]['is_jp']?'精品':'热门';
                $data[$k]['user_count'] =db('jp_user')->where('goods_id',$v['goods_id'])->count('id');
                $data[$k]['count'] =db('jp_bill')->where('goods_id',$v['goods_id'])->count('id');

                $new_user=db('jp_bill')->where('goods_id',$v['goods_id'])->order('price desc')->find();
                if($new_user) {
                    $data[$k]['new_price']=$new_user['price'];
                }
                else $data[$k]['new_price']=$data[$k]['payable'];

                $data[$k]['jp_status']=$data[$k]['end_time']>time()?'拍卖中':'已结束';
                if($data[$k]['status']==0)
                {
                    $data[$k]['jp_status']='未开始';
                }

            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('shoppingmall/goods_jp_list');
        }
    }

    //获取竞拍的用户列表
    public function user_list()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = db('jp_bill');
            $where = $this->_param;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->where('goods_id', $this->_param['goods_id'])->order('id desc') : $data = $list->where('goods_id', $this->_param['goods_id'])->order('id desc');

            $t_list = clone ($list);
            $total = $t_list->count();
            $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
            $data = $list->select();

            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $data[$k]['create_time'] = $data[$k]['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '';
                $user=\app\api\model\Member::get(['id'=>$v['uid']]);
                if($user) $new_user['nickname']=$user['nickname'];
                $data[$k]['nickname']= $user['nickname'];
                $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            $this->assign('goods_id', $this->_param['goods_id']);
            return $this->fetch('shoppingmall/user_list');
        }
    }

    //是否设置为热门
    public function is_hot()
    {
        $id = $this->_param['id'];
        if (isset($this->_param['cancle'])) {
            $res = DB::name('goods')->where('goods_id', $id)->update(['is_hot' => 0]);
            $this->ajaxReturn('取消成功', '', '', '200');
        } else {
            $res = DB::name('goods')->where('goods_id', $id)->update(['is_hot' => 1]);
            $this->ajaxReturn('置顶成功', '', '', '200');
        }
    }

    //商品审核列表
    public function goods_examine()
    {
//      $list = db('goods')->where('status',-1)->order('goods_id desc')->select();
//       dump($list);die;
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = Db::name('goods')->order('goods_id desc');
            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
//            $where['status'] = -1;
            (!empty($where)) ? $list = $list->whereor($where) : $list = $list->where('status',-1);
            $list1= clone($list);
            $to = $list->count();
            $list = $list1;
            $res  =   $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit'])->select();
            $this->assign('map', $this->_param);
            foreach ($res as $k => $v){
                $member = Member::get(['id' => $v['uid']]);
//              if(empty($member))continue;
                $res[$k]['nickname'] = $member->nickname;
                $res[$k]['img']      = $this->url.'/uploads/goods/'.$res[$k]['image'];
            }
            $this->ajaxReturn('', $res,$to);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('shoppingmall/goods_examine');
        }
    }

    //商品审核列表 查看详情
    public function goods_examine_info($goods_id){
        $list = db('goods')->where('goods_id',$goods_id)->find();
        $list['img'] = $this->url.'/uploads/goods/'.$list['image'];
        $list['imglist'] = explode(',',$list['imglist']);
        $Category = Category::get(['id' => $list['category_id']]);
        $list['category'] = $Category->name;
        foreach ($list['imglist'] as   $k=>$v){
            $list['imglist'][$k]  = getFileUrl($v,'goods');
        }
//      dump($list);die;
        $this->assign('list',$list);
        return $this->fetch();
    }
    //商品通过审核
    public function examine($id)
    {
//        $res = input();
//        $ids = isset($res['id']) ? $res['id'] : 0;
        $res = Goods::where('goods_id', 'in', $id)->update(['status' => 1,'end_time'=>strtotime('+1day')]);
        if ($res !== false) {
//            $this->success('上架成功!', url('goods_examine'));
            $this->ajaxReturn('上架成功!', 200);
        } else {
//            $this->error('上架失败!', '');
            $this->ajaxReturn('上架失败', 201);
        }
    }

    //商品未通过审核
    public function no_examine($id)
    {
//        $res = input();
//        $ids = isset($res['id']) ? $res['id'] : 0;
        $res = Goods::where('goods_id', 'in', $id)->update(['status' => -2]);
        if ($res !== false) {
//            $this->success('上架成功!', url('goods_examine'));
            $this->ajaxReturn('已拒绝通过审核!', 200);
        } else {
//            $this->error('上架失败!', '');
            $this->ajaxReturn('拒绝通过审核失败', 201);
        }
    }

    //商品下架
    public function goods_dismount()
    {
        $res = input();
        $ids = isset($res['id']) ? $res['id'] : 0;
        $res = Goods::where('goods_id', 'in', $ids)->update(['status' => 0]);
        if ($res !== false) {
//            $this->success('上架成功!', url('goods_examine'));
            $this->ajaxReturn('商品下架成功!', 200);
        } else {
//            $this->error('上架失败!', '');
            $this->ajaxReturn('商品下架失败!', 201);
        }
    }

    //商品上架
    public function goods_Shelves()
    {
        $res = input();
        $ids = isset($res['id']) ? $res['id'] : 0;
        $res = Goods::where('goods_id', 'in', $ids)->update(['status' => 1]);
        if ($res !== false) {
//            $this->success('上架成功!', url('goods_examine'));
            $this->ajaxReturn('商品上架成功!', 200);
        } else {
//            $this->error('上架失败!', '');
            $this->ajaxReturn('商品上架失败!', 201);
        }
    }

    //商品列表查看详情
    public function goods_info($id)
    {

        $list = db('goods')->where('goods_id', $id)->find();
        $list['category_id'] = db('category')->where('id',$list['category_id'])->value('name');
        $list['create_time'] = date('Y-m-d,H:i:s', $list['create_time']);
        $status = $this->goods_status();
        $list['status'] = $status[$list['status']];
        $list['img'] = $this->url.'/uploads/goods/'.$list['image'];
        $this->assign('list', $list);
        return $this->fetch();

    }

    //公告
    public function notice()
    {
        if (isset($this->_param['op']) && $this->_param['op'] == 'table') {
            $list = Db::name('notice')->order('notice_id desc');
            $total = $list->count();
            $list->limit(($this->_param['page'] - 1) * $this->_param['limit'], $this->_param['limit']);
            $where = $this->_map;
            unset($where['page']);
            unset($where['op']);
            unset($where['limit']);
            (!empty($where)) ? $data = $list->whereor($where)->select() : $data = $list->select();
            $this->assign('map', $this->_param);
            foreach ($data as $k => $v) {
                $data[$k]['create_time'] = date('Y-m-d,H:i:s', $v['create_time']);
            }
            $this->ajaxReturn('', $data, $total);
        }
        if (!isset($this->_param['op'])) {
            return $this->fetch('shoppingmall/notice');
        }
    }

    //上传公告
    public function add_notice()
    {
        $validate = [
            ['title', 'require', '标题不能为空',],
            ['content', 'require', '详情不能为空'],
        ];
        $text = $this->validate($this->_param, $validate);
        if ($text !== true) {
            $this->ajaxReturn($text, 201);
        }
        $user = new Notice;
        $user->title = $this->_param['title'];
        $user->content = $this->_param['content'];
        $user->create_time = time();
        $rv = $user->save();
        if ($rv) {
            $this->ajaxReturn('保存成功', 200);
        } else {
            $this->ajaxReturn('保存失败', 201);
        }
    }

    //修改公告
    public function up_notice()
    {
        $validate = [
            ['title', 'require', '标题不能为空',],
            ['content', 'require', '详情不能为空'],
        ];
        $text = $this->validate($this->_param, $validate);
        if ($text !== true){
            $this->ajaxReturn($text, 201);
        }
        $user = Notice::get(['notice_id'=>$this->_param['notice_id']]);
        $user->title   = $this->_param['title'];
        $user->content = $this->_param['content'];
        $user->create_time =time();
        $rv =$user->isUpdate(true)->save();
        if ($rv) {
            $this->ajaxReturn('保存成功', 200);
        } else {
            $this->ajaxReturn('保存失败', 201);
        }
    }

    //删除公告
    public function delete_notice(){
        $id =    $this->_param['id'];
        $bt = Notice::destroy(['notice_id'=>$id]);
        if($bt){
            $this->ajaxReturn('删除成功',200);
        }else{
            $this->ajaxReturn('删除失败',201);
        }
    }

}
